package com.wzg.jetpack_blackbox.login;

import android.app.Application;
import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.Observable;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.wzg.jetpack_blackbox.base.INetWorkCallback;
import com.wzg.jetpack_blackbox.login.entity.LoginEntity;
import com.wzg.jetpack_blackbox.main.MainActivity;

public class LoginViewModel extends AndroidViewModel {


    public ObservableField<String> name = new ObservableField<>("");
    public ObservableField<String> pwd = new ObservableField<>("");


    private final LoginRepository loginRepository;


    public LoginViewModel(@NonNull Application application) {
        super(application);
        loginRepository = LoginRepository.getInstance();
    }


    public void onSubmitListener(View v) {


        LogUtils.iTag("login", "name: " + (name.get()) + "\tpwd: " + (pwd.get()));
        loginRepository.login(name.get(), pwd.get(), new INetWorkCallback<LoginEntity>() {
            @Override
            public void onSuccess(LoginEntity data) {
                if (data != null) {
                    loginRepository.save2disk(data.getLoginName(), data.getToken());
                    ToastUtils.showLong("登陆或注册成功");
                }
                Intent intent = new Intent(getApplication(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ThreadUtils.getMainHandler().postDelayed(() -> getApplication().startActivity(intent), 500);
            }

            @Override
            public void onFailed(String message) {
                //show toast.
                ToastUtils.showLong(message);
            }
        });
    }


}
